package com.lancoo.znbkxx.teacher.ui.fragment

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.graphics.Typeface
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.view.size
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter
import com.lancoo.znbkxx.teacher.Ext
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.adapter.QuestionListAdapter
import com.lancoo.znbkxx.teacher.adapter.SpacesItemDecoration
import com.lancoo.znbkxx.teacher.adapter.WrongCommentAdapter
import com.lancoo.znbkxx.teacher.base.BaseVMFragment
import com.lancoo.znbkxx.teacher.databinding.FmtComment1v1Binding
import com.lancoo.znbkxx.teacher.model.OperationHelp
import com.lancoo.znbkxx.teacher.model.data.Ques
import com.lancoo.znbkxx.teacher.ui.activity.CommentDetailActivity
import com.lancoo.znbkxx.teacher.utils.DensityUtils
import com.lancoo.znbkxx.teacher.utils.HtmlUtils
import com.lancoo.znbkxx.teacher.viewmodel.HardSolutionViewModel
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener

import kotlinx.android.synthetic.main.fmt_comment_1v1.*
import kotlinx.android.synthetic.main.fmt_comment_1v1.chart
import kotlinx.android.synthetic.main.fmt_comment_1v1.swipe_layout
import kotlinx.android.synthetic.main.fmt_comment_1v1.tv_recommend
import kotlinx.android.synthetic.main.fmt_comment_1v1.tv_stuname
import kotlinx.android.synthetic.main.fmt_comment_1v1.tv_title
import kotlinx.android.synthetic.main.fmt_skillcomment.*


/**
 * Created by wealive on 2021/3/16.
 *
 *
 */
class WrongCommentFragment : BaseVMFragment<HardSolutionViewModel, FmtComment1v1Binding>(),
        BaseQuickAdapter.OnItemChildClickListener, BaseQuickAdapter.OnItemClickListener {
    private val commentList = mutableListOf<Ques>()
    private lateinit var commentAdapter: WrongCommentAdapter
    private val answerEntries = mutableListOf<Entry>()
    private val wrongEntries = mutableListOf<Entry>()
    private val xLabels = mutableListOf<String>()
    private var pageSize = 10
    private var totalCount = 0
    override fun providerVMClass(): Class<HardSolutionViewModel>? {
        return HardSolutionViewModel::class.java
    }

    override fun providerContext(): Any? {
        return this
    }

    override fun setLayoutID(): Int {
        return R.layout.fmt_comment_1v1
    }

    override fun initView() {
        tv_title.typeface = Typeface.createFromAsset(requireContext().assets,
                "fonts/cool_black.TTF")
        initComment()
    }

    private fun initComment() {
        val manager = LinearLayoutManager(requireContext())
        rv_comment.layoutManager = manager
        commentAdapter = WrongCommentAdapter(commentList)
        commentAdapter.setHeaderFooterEmpty(false, true)
        val emptyView = layoutInflater.inflate(R.layout.empty_view, null)
        commentAdapter.emptyView = emptyView
        commentAdapter.onItemChildClickListener = this
        commentAdapter.onItemClickListener = this
        val map = hashMapOf<String, Int>()
        map[SpacesItemDecoration.TOP_SPACE] = DensityUtils.dp2px(requireContext(), 5f)
        map[SpacesItemDecoration.BOTTOM_SPACE] = DensityUtils.dp2px(requireContext(), 5f)
        val itemDecoration = SpacesItemDecoration(map)
        rv_comment.addItemDecoration(itemDecoration)
        rv_comment.adapter = commentAdapter
        swipe_layout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageSize = 10
                getWrongComment()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                if (totalCount >= pageSize) {
                    pageSize += 10
                    getWrongComment()
                }
            }
        })
    }

    private fun initChart(total: Int) {
        val xAxis: XAxis = chart.xAxis
        chart.apply {
            val answerDataSet = LineDataSet(answerEntries, "")
            answerDataSet.apply {
                color = Color.parseColor("#2dbcff")
                lineWidth = 1f
                setDrawCircleHole(false)
                setDrawCircles(false)
                setDrawFilled(true)
                fillDrawable = ContextCompat.getDrawable(requireContext(),
                        R.drawable.aibk_bg_linechart)
                mode = LineDataSet.Mode.CUBIC_BEZIER
            }
            val wrongDataset = LineDataSet(wrongEntries, "")
            wrongDataset.apply {
                color = Color.parseColor("#f97676")
                lineWidth = 1f
                setDrawCircleHole(false)
                setDrawCircles(false)
                setDrawFilled(true)
                fillDrawable = ContextCompat.getDrawable(requireContext(),
                        R.drawable.aibk_bg_linechart3)
                mode = LineDataSet.Mode.CUBIC_BEZIER
            }
            val lineChartData = LineData(answerDataSet, wrongDataset)
            lineChartData.setDrawValues(false)
            data = lineChartData
            axisLeft.apply {
                setDrawGridLines(false)
                textSize = 11f
                textColor = Color.parseColor("#999999")
                spaceBottom = 0f
                axisMinimum = 0f
                axisMaximum = total.toFloat() + 10f
            }
            axisRight.isEnabled = false
            legend.isEnabled = false
            description.isEnabled = false
            setPinchZoom(false)
            setScaleEnabled(false)
            xAxis.apply {
                axisMinimum = -0.5f
                axisMaximum = answerEntries.size + 1f
                textColor = Color.parseColor("#999999")
                textSize = 11f
                position = XAxis.XAxisPosition.BOTTOM
                setDrawAxisLine(true)
                setDrawGridLines(false)
                valueFormatter = IndexAxisValueFormatter(xLabels)
            }
            animateX(1000)
        }
    }

    override fun startObserve() {
        viewModel.wrongCommentInfo.observe(this, Observer {
            xLabels.clear()
            answerEntries.clear()
            wrongEntries.clear()
            tv_wrong_num.text = it.TotalCount.toString()
            tv_new_num.text = it.NewWrongNum.toString()
            tv_uncommented.text = (it.TotalCount - it.CommentCount).toString()
            tv_commented.text = it.CommentCount.toString()
            totalCount = it.TotalCount
            tv_recommend.text = HtmlUtils.setText(
                    getString(R.string.recommend_type, it.TotalCount.toString()))
            commentList.clear()
            commentList.addAll(it.QuesList)
            commentAdapter.setNewData(commentList)
            swipe_layout.finishRefresh()
            swipe_layout.setEnableLoadMore(pageSize < it.TotalCount)
            if (pageSize == it.TotalCount) {
                swipe_layout.finishLoadMoreWithNoMoreData()
            } else {
                swipe_layout.finishLoadMore()
            }
            it.Statistics.forEachIndexed { index, statistic ->
                val answerEntry = Entry(index.toFloat(), statistic.AnswerCount.toFloat())
                val wrongEntry = Entry(index.toFloat(), statistic.WrongCount.toFloat())
                answerEntries.add(answerEntry)
                wrongEntries.add(wrongEntry)
                val time = statistic.Date
                xLabels.add(time)
            }
            if (it.Statistics.isNotEmpty()) {
                initChart(it.TotalCount)
            }
        })
    }


    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        val dataList = (adapter as WrongCommentAdapter).data
        startActivity(Intent(activity, CommentDetailActivity::class.java).apply {
            putExtra("QuesID", dataList[position].QuesID)
            putExtra("isCommented", dataList[position].IsComment)
            putExtra("isOneOnOne", true)
        })
    }


    override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        val dataList = (adapter as WrongCommentAdapter).data
        startActivity(Intent(activity, CommentDetailActivity::class.java).apply {
            putExtra("QuesID", dataList[position].QuesID)
            putExtra("isCommented", dataList[position].IsComment)
            putExtra("isOneOnOne", true)
        })
    }

    @SuppressLint("SetTextI18n")
    override fun onResume() {
        super.onResume()
        tv_stuname.text = "${Ext.STU_NAME}的答题情况统计"
        getWrongComment()
    }

    private fun getWrongComment() {
        viewModel.getWrongComment(Ext.STU_ID, 1, pageSize)
    }
}